package com.vlong.town.controller.admin.organization;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.vlong.town.controller.base.BaseController;
import com.vlong.town.entity.base.DataMessage;
import com.vlong.town.entity.organization.Organization;
import com.vlong.town.service.organization.OrganizationService;
import com.vlong.town.util.common.TownConstant;
import com.vlong.town.util.date.DateUtil;

import javax.servlet.ServletOutputStream;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/org")
public class OrganizationController extends BaseController{

	@Autowired
	private  OrganizationService  organizationService;
	
	/**
	 * 商家管理
	 * @return
	 */
	@RequestMapping("/list")
	public  String  list(){
		return  "admin/org/list_org";
	}
	
	/**
	 * 商家统计
	 * @return
	 */
	@RequestMapping("/listNum")
	public  String  listNum(){
		return  "admin/org/listNum_org";
	}
	
	
	
	/**
	 * 查询机构
	 * @param orgName
	 * @param orgPhone
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/treeTable")
	public  DataMessage  treeTable(
            @RequestParam(required=false, value="orgName") String orgName,
            @RequestParam(required=false, value="orgPhone") String orgPhone
			){
		// 返回数据消息实体
		DataMessage dm = new DataMessage();
		List<Organization> resultList = new ArrayList<Organization>();
        List<Organization> orgList = organizationService.queryList(null, null, null, 1, TownConstant.DEL_FLAG_0, null, null, null, null, orgName, null, null, orgPhone, null, null, null, null, null, null, null, null, null, null, null, null, null);
        for(Organization org : orgList) {
			if(org.getOrgLevel().intValue() == 1) {
				this.recursionSubOrg(resultList, org);
			}
		}
        dm.setResult(TownConstant.RESULT_CODE_SUCCESS);
		dm.setData(resultList);
		return  dm;
	}
	
	
	/**
	 * 递归添加机构子集
	 * @param resultList 结果List
	 * @param parentOrg 父级机构
	 */
	private void recursionSubOrg(List<Organization> resultList, Organization parentOrg) {
		if(parentOrg.getIsParent().intValue() == 1) {
			List<Organization> subList = this.organizationService.querySubList(parentOrg.getOrgId());
			parentOrg.setSubList(subList);
			resultList.add(parentOrg);
			for(Organization sub : subList) {
				if(sub.getIsParent().intValue() == 1) {
					recursionSubOrg(resultList, sub);
				}
			}
		} else {
			resultList.add(parentOrg);
		}
	}
	
	/**
     * 跳转机构添加页面
     * @return String
     */
    @RequestMapping("/addOrg")
    public  String  addOrg(){
    	return  "admin/org/add_org";
    }
	
	
    /**
     * 添加机构
     * @param orgName
     * @param orgAliasName
     * @param orgPhone
     * @param orgFax
     * @param orgWebsite
     * @param orgDesc
     * @param orgAddress
     * @return
     */
    @ResponseBody
    @RequestMapping("/executeAddOrg")
    public  DataMessage  executeAddOrg(
    		@RequestParam(required=false, value="orgName") String orgName,
    		@RequestParam(required=false, value="orgAliasName") String orgAliasName,
    		@RequestParam(required=false, value="orgPhone") String orgPhone,
    		@RequestParam(required=false, value="orgFax") String orgFax,
    		@RequestParam(required=false, value="orgWebsite") String orgWebsite,
    		@RequestParam(required=false, value="orgDesc") String orgDesc,
    		@RequestParam(required=false, value="orgAddress") String orgAddress
    		){
    	DataMessage dm=new DataMessage();
    	if(!this.validateStringProperty(orgName, 1, 50)) {
            dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("机构名称不合法");
        }else if(!this.validateStringProperty(orgAliasName, 1, 50)){
        	 dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
             dm.setMessage("机构别名不合法");
        }else if(!this.validateStringProperty(orgPhone, 1, 50)){
	       	 dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
	         dm.setMessage("机构电话不合法");
        }else if(!this.validateStringProperty(orgFax, 1, 50)){
	       	 dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
	         dm.setMessage("机构传真不合法");
        }else if(!this.validateStringProperty(orgWebsite, 1, 50)){
	       	 dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
	         dm.setMessage("机构网址不合法");
        }else{
        	this.organizationService.add(null, null, 1, 1, TownConstant.DEL_FLAG_0, null, 1, 0, 0L, orgName, orgAliasName, orgDesc, orgPhone, orgFax, orgWebsite, null, null, null, orgAddress, null, null, null, null, null, System.currentTimeMillis(), null);
        	dm.setResult(TownConstant.RESULT_CODE_SUCCESS);
            dm.setMessage("机构添加成功");
        }
    	return  dm;
    }
    
    /**
     * 添加根机构
     * @param orgPid
     * @param orgName
     * @param orgAliasName
     * @param orgPhone
     * @param orgFax
     * @param orgWebsite
     * @param orgDesc
     * @param orgAddress
     * @return
     */
    @ResponseBody
    @RequestMapping("/executeAddSubOrg")
    public  DataMessage  executeAddSubOrg(
    		@RequestParam(required=false, value="orgPid") String orgPid,
    		@RequestParam(required=false, value="orgName") String orgName,
    		@RequestParam(required=false, value="orgAliasName") String orgAliasName,
    		@RequestParam(required=false, value="orgPhone") String orgPhone,
    		@RequestParam(required=false, value="orgFax") String orgFax,
    		@RequestParam(required=false, value="orgWebsite") String orgWebsite,
    		@RequestParam(required=false, value="orgDesc") String orgDesc,
    		@RequestParam(required=false, value="orgAddress") String orgAddress
    		){
    	DataMessage dm=new DataMessage();
    	if(!this.validateStringProperty(orgName, 1, 50)) {
            dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("机构名称不合法");
        }else if(!this.validateStringProperty(orgAliasName, 1, 50)){
        	 dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
             dm.setMessage("机构别名不合法");
        }else if(!this.validateStringProperty(orgPhone, 1, 50)){
	       	 dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
	         dm.setMessage("机构电话不合法");
        }else if(!this.validateStringProperty(orgFax, 1, 50)){
	       	 dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
	         dm.setMessage("机构传真不合法");
        }else if(!this.validateStringProperty(orgWebsite, 1, 50)){
	       	 dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
	         dm.setMessage("机构网址不合法");
        }else{
        	this.organizationService.addSub(Long.parseLong(orgPid),orgName,orgAliasName,orgPhone,orgFax,orgWebsite,orgDesc,orgAddress);
        	dm.setResult(TownConstant.RESULT_CODE_SUCCESS);
            dm.setMessage("机构添加成功");
        }
    	return  dm;
    }
	
    /**
     * 跳转添加跟机构页面
     * @param orgPid 父级id
     * @return String
     */
    @RequestMapping("/addSubOrg")
    public  String  addSubOrg(@RequestParam(required=false, value="orgPid") String orgPid){
    	request.setAttribute("orgPid", orgPid);
    	return  "admin/org/add_sub_org";
    }
    
    
    /**
     * 根据机构id查询机构
     * @param orgId 机构Id
     * @return
     */
    @RequestMapping("/editOrg")
    public  String  editOrg(@RequestParam(required=false, value="orgId") Long orgId){
    	Organization org = this.organizationService.queryById(orgId);
    	request.setAttribute("org", org);
    	return  "admin/org/edit_org";
    }
	
    
    /**
     * 添加机构
     * @param orgName
     * @param orgAliasName
     * @param orgPhone
     * @param orgFax
     * @param orgWebsite
     * @param orgDesc
     * @param orgAddress
     * @return
     */
    @ResponseBody
    @RequestMapping("/executeEditOrg")
    public  DataMessage  executeEditOrg(
    		@RequestParam(required=false, value="orgId") Long orgId,
    		@RequestParam(required=false, value="orgName") String orgName,
    		@RequestParam(required=false, value="orgAliasName") String orgAliasName,
    		@RequestParam(required=false, value="orgPhone") String orgPhone,
    		@RequestParam(required=false, value="orgFax") String orgFax,
    		@RequestParam(required=false, value="orgWebsite") String orgWebsite,
    		@RequestParam(required=false, value="orgDesc") String orgDesc,
    		@RequestParam(required=false, value="orgAddress") String orgAddress
    		){
    	DataMessage dm=new DataMessage();
    	if(!this.validateStringProperty(orgName, 1, 50)) {
            dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("机构名称不合法");
        }else if(!this.validateStringProperty(orgAliasName, 1, 50)){
        	 dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
             dm.setMessage("机构别名不合法");
        }else if(!this.validateStringProperty(orgPhone, 1, 50)){
	       	 dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
	         dm.setMessage("机构电话不合法");
        }else if(!this.validateStringProperty(orgFax, 1, 50)){
	       	 dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
	         dm.setMessage("机构传真不合法");
        }else if(!this.validateStringProperty(orgWebsite, 1, 50)){
	       	 dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
	         dm.setMessage("机构网址不合法");
        }else{
        	this.organizationService.edit(orgId, null, null, null, null, null, null, null, null, orgName, orgAliasName, orgDesc, orgPhone, orgFax, orgWebsite, null, null, null, orgAddress, null, null, null, null, null, null, System.currentTimeMillis());
        	dm.setResult(TownConstant.RESULT_CODE_SUCCESS);
            dm.setMessage("机构修改成功");
        }
    	return  dm;
    }
    
    
   /**
    * 删除机构
    * @param orgId  机构id
    * @return DataMessage
    */
    @ResponseBody
    @RequestMapping("/delete")
    public  DataMessage  delete(@RequestParam(required=false, value="orgId") Long orgId){
    	DataMessage dm = new DataMessage();
    	if(orgId != null && orgId > 0L) {
    		organizationService.editIsDel(orgId, TownConstant.DEL_FLAG_1);
            dm.setResult(TownConstant.RESULT_CODE_SUCCESS);
            dm.setMessage("机构删除成功");
        } else {
            dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("参数错误");
        }
        return dm;
    }
   
    /**
     * 批量删除机构
     * @param orgIds
     * @return
     */
    @ResponseBody
    @PostMapping("/batchDelete")
    public DataMessage batchDeleteUser(@RequestParam(required=true, value="orgIds") String orgIds) {
        DataMessage dm = new DataMessage();
        if(this.validateStringProperty(orgIds, 1, 128)) {
            String[] orgIdsArray = orgIds.split(",");
            for(String orgId : orgIdsArray) {
            	organizationService.editIsDel(Long.parseLong(orgId), 1);
            }
            dm.setResult(TownConstant.RESULT_CODE_SUCCESS);
            dm.setMessage("机构删除成功");
        } else {
            dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("参数错误");
        }
        return dm;
    }
	/**
	 * 导出客户统计信息数据到Excel
	 * @return Excel File
	 * @throws Exception
	 */
	@PostMapping("/exportOrg")
	public ModelAndView exportOrg(
			@RequestParam(required=false, value="orgName_org") String orgName,
			@RequestParam(required=false, value="orgPhone_org") String orgPhone
	) throws Exception {
		Workbook wb = new HSSFWorkbook();
		Sheet sheet = wb.createSheet("客户统计");
		// 手动设置列宽。第一个参数表示要为第几列设；，第二个参数表示列的宽度，n为列高的像素数。
		sheet.setColumnWidth((short) 0, (short) (15.7 * 150));
		sheet.setColumnWidth((short) 1, (short) (25.7 * 150));
		sheet.setColumnWidth((short) 2, (short) (35.7 * 150));
		sheet.setColumnWidth((short) 3, (short) (35.7 * 150));
		sheet.setColumnWidth((short) 4, (short) (35.7 * 150));
		sheet.setColumnWidth((short) 5, (short) (35.7 * 150));
		sheet.setColumnWidth((short) 6, (short) (35.7 * 150));
		sheet.setColumnWidth((short) 7, (short) (35.7 * 150));
		Row row = sheet.createRow((short) 0);
		// 创建两种单元格格式
		CellStyle cs = wb.createCellStyle();
		CellStyle cs2 = wb.createCellStyle();

		// 创建两种字体
		Font f = wb.createFont();
		Font f2 = wb.createFont();

		// 创建第一种字体样式
		f.setFontHeightInPoints((short) 12);
		f.setColor(IndexedColors.BLACK.getIndex());
		f.setBoldweight(Font.BOLDWEIGHT_BOLD);
		// 创建第二种字体样式
		f2.setFontHeightInPoints((short) 11);
		f2.setColor(IndexedColors.BLACK.getIndex());
		f2.setBoldweight(Font.BOLDWEIGHT_NORMAL);

		// 设置第一种单元格的样式
		cs.setFont(f);
		cs.setBorderLeft(CellStyle.BORDER_THIN);
		cs.setBorderRight(CellStyle.BORDER_THIN);
		cs.setBorderTop(CellStyle.BORDER_THIN);
		cs.setBorderBottom(CellStyle.BORDER_THIN);
		cs.setAlignment(HSSFCellStyle.ALIGN_LEFT);

		// 设置第二种单元格的样式
		cs2.setFont(f2);
		cs2.setBorderLeft(CellStyle.BORDER_THIN);
		cs2.setBorderRight(CellStyle.BORDER_THIN);
		cs2.setBorderTop(CellStyle.BORDER_THIN);
		cs2.setBorderBottom(CellStyle.BORDER_THIN);
		cs2.setAlignment(HSSFCellStyle.ALIGN_LEFT);

		// 创建列（每行里的单元格）
		Cell cell = row.createCell(0);
		cell.setCellValue("机构名称");
		cell.setCellStyle(cs);

		cell = row.createCell(1);
		cell.setCellValue("机构别名");
		cell.setCellStyle(cs);

		cell = row.createCell(2);
		cell.setCellValue("机构电话");
		cell.setCellStyle(cs);

		cell = row.createCell(3);
		cell.setCellValue("机构传真");
		cell.setCellStyle(cs);

		cell = row.createCell(4);
		cell.setCellValue("机构网址");
		cell.setCellStyle(cs);

		cell = row.createCell(5);
		cell.setCellValue("机构说明");
		cell.setCellStyle(cs);

		cell = row.createCell(6);
		cell.setCellValue("添加时间");
		cell.setCellStyle(cs);

		cell = row.createCell(7);
		cell.setCellValue("更新时间");
		cell.setCellStyle(cs);

		// 查询要导出的客户统计数据
		List<Organization> orgList = organizationService.queryList(null, null, null, 1, TownConstant.DEL_FLAG_0, null, null, null, null, orgName, null, null, orgPhone, null, null, null, null, null, null, null, null, null, null, null, null, null);
		for(int i = 0; i < orgList.size(); i++) {
			Organization organization = orgList.get(i);

			row = sheet.createRow(i + 1);
			cell = row.createCell(0);
			cell.setCellValue(organization.getOrgName());
			cell.setCellStyle(cs2);

			cell = row.createCell(1);
			cell.setCellValue(organization.getOrgAliasName());
			cell.setCellStyle(cs2);

			cell = row.createCell(2);
			cell.setCellValue(organization.getOrgPhone());
			cell.setCellStyle(cs2);

			cell = row.createCell(3);
			cell.setCellValue(organization.getOrgFax());
			cell.setCellStyle(cs2);

			cell = row.createCell(4);
			cell.setCellValue(organization.getOrgWebsite());
			cell.setCellStyle(cs2);

			cell = row.createCell(5);
			cell.setCellValue(organization.getOrgDesc());
			cell.setCellStyle(cs2);

			cell = row.createCell(6);
			cell.setCellValue(DateUtil.formatDateTime(organization.getCreateTime()));
			cell.setCellStyle(cs2);

			cell = row.createCell(7);
			cell.setCellValue(DateUtil.formatDateTime(organization.getUpdateTime()));
			cell.setCellStyle(cs2);
		}
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			wb.write(os);
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] content = os.toByteArray();
		InputStream is = new ByteArrayInputStream(content);
		response.reset();
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		response.setHeader("Content-Disposition", "attachment;filename=" + new String(("商家统计" + ".xls").getBytes(), "ISO-8859-1"));
		ServletOutputStream out = response.getOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (final IOException e) {
			throw e;
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}
		return null;
	}
	
}
